package ts

import (
	"fmt"
	"gitee.com/xiaochengtech/unified-structure/src/common"
	"gitee.com/xiaochengtech/unified-structure/src/util"
	"log"
	"sort"
	"strings"
)

// 注册语言处理插件
func init() {
	common.Plugins[common.LanguageTs] = new(Process)
}

// 需要实现common.Plugin的结构体
type Process struct {
	indexMap map[string]string // index.ts中的导出项，key为导出名称，value为文件名称
}

// 获取生成文件的内容
func (m *Process) GetMainFile(ctx common.Context) (filename string, content string) {
	lines := make([]string, 0)
	if ctx.File.HasComment() {
		lines = append(lines, fmt.Sprintf("// %s", ctx.File.Comment))
		lines = append(lines, "")
	}
	if ctx.Dir.IsConstant() {
		lines = append(lines, constantFile(ctx)...)
	} else if ctx.Dir.IsModel() {
		lines = append(lines, modelFile(ctx)...)
	} else {
		log.Fatalln("模式错误", ctx.Dir.Mode)
	}
	// 添加导出项
	// TODO init方式
	if m.indexMap == nil {
		m.indexMap = make(map[string]string)
	}
	m.indexMap[ctx.File.Name] = ctx.CurFileName
	// 结果
	filename = ctx.CurFileName + ".ts"
	content = strings.Join(lines, "\n")
	return
}

// 获取其他文件的内容
func (m *Process) GetOtherFile(ctx common.Context) (filename string, content string) {
	// TODO 清理nil
	if m.indexMap == nil || len(m.indexMap) == 0 {
		return
	}
	exportItems := make([]string, 0)
	lines := make([]string, 0)
	keys := make([]string, 0)
	for key, _ := range m.indexMap {
		keys = append(keys, key)
	}
	sort.Strings(keys)
	for _, itemName := range keys {
		filePath := m.indexMap[itemName]
		if ctx.Dir.IsConstant() {
			lines = append(lines, fmt.Sprintf("import * as %s from './%s';", itemName, filePath))
		} else if ctx.Dir.IsModel() {
			lines = append(lines, fmt.Sprintf("import { %s } from './%s';", itemName, filePath))
		}
		exportItems = append(exportItems, itemName)
	}
	lines = append(lines, "")
	lines = append(lines, "export {")
	for _, exportItem := range exportItems {
		lines = append(lines, util.TabStop(fmt.Sprintf("%s,", exportItem), 1))
	}
	lines = append(lines, fmt.Sprintf("};"))
	// 结果
	filename = "index.ts"
	content = strings.Join(lines, "\n")
	// 清空 TODO
	m.indexMap = nil
	return
}

// 是否可以拷贝
func (m *Process) CanCopy(ctx common.Context, fileName string) bool {
	for _, ext := range ctx.Dir.ExtTs.CopyExt {
		if strings.Contains(fileName, ext) {
			return true
		}
	}
	return false
}
